<template>
  <!--按任务工分登记-->
  <BasicModal v-bind="$attrs" @register="registerModal" title="按任务登记" @ok="handleSubmit" width="100%" :defaultFullscreen="true" :destroyOnClose="true" :showOkBtn="!isView" :okButtonProps="{ loading: okLoading, }">
    <div class="table-container">
      <!-- 左侧-工分类型树 -->
      <list :options="workTree" @select="handleWorkTreeSelect" ref="workList" />
      <div class="table-content" style="margin-left: 10px">
        <BasicForm @register="registerForm" />
        <div class="bot-container">
          <!-- 右侧-人员树 -->
          <list :options="userTree" @select="handleUserTreeSelect" ref="userList" />
          <!-- 右侧登记表 -->
          <div class="bot-table-container">
            <BasicTable @register="registerTable">
              <template #bodyCell="{ column, text, record, index }">
                <template v-if="column.editRow">
                  <a-input-number :disabled="isView" v-model:value="record[column.dataIndex]" @change="scoreCompute" v-if="'InputNumber' === column.editComponent && column.dataIndex === 'unit'" @focus="handleIndex(index)" :min="1" />
                  <a-input-number :disabled="isView" v-model:value="record[column.dataIndex]" @change="scoreCompute" v-if="'InputNumber' === column.editComponent && column.dataIndex === 'qspoints'" @focus="handleIndex(index)" />
                  <a-select :disabled="isView" v-model:value="record[column.dataIndex]" style="width: 100%" @change="scoreCompute" @focus="handleIndex(index)" :options="column.options" :fieldNames="{ label: 'workName', value: 'workCode' }" v-else-if="'Select' === column.editComponent" />
                  <a-input :disabled="isView" v-model:value="record[column.dataIndex]" @change="scoreCompute" v-else-if="column.dataIndex === 'workExpl'" />
                </template>
              </template>
              <template #action="{ record, index }">
                <TableAction :actions="getTableAction(record, index)" />
              </template>
            </BasicTable>
          </div>
        </div>
      </div>
    </div>
  </BasicModal>
</template>
<script setup>
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { taskColumns } from './HubTeamResultWork.data';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { createPoints, getOptions, getTaskContentDetail, getTaskDetail, showModeSelect, getWorkTreeApi, getUserTreeApi, getColumn, save, getWorkTreeList, } from './HubTeamResultWork.api';
// import execMathExpress from 'exec-mathexpress';
import { unifyNumber } from '/@/views/zhc/util/numUtils';
import { useMessage } from '/@/hooks/web/useMessage';
import dayjs from 'dayjs';

const props = defineProps({
  self: {
    type: String,
  },
});
let pageParams = ref({
  orgCode: '',
  orgName: '',
  periodCode: '',
});
const okLoading = ref(false);
let isView = ref(false);
const handleIndex = (index) => {
  currentTableIndex = index;
};
let workTreeList = ref([]);
let currentTableIndex = 0; //记录当前操作的表格数据行
let userList = ref(null);
let workList = ref(null);
const { createMessage } = useMessage();
const taskForm = [
  {
    field: 'workItemName',
    label: '工作项',
    component: 'Input',
    dynamicDisabled: () => true,
    colProps: { span: 8 },
  },
  {
    field: 'workItemCode',
    label: '工作项目编码',
    component: 'Input',
    show: false,
  },
  {
    field: 'endDate',
    label: '工作时间',
    component: 'DatePicker',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
    },
    defaultValue: dayjs(),
    required: true,
    colProps: { span: 8 },
    dynamicDisabled: () => isView.value,
  },
  {
    field: 'standardValue',
    label: '标准分值',
    component: 'Input',
    colProps: { span: 8 },
    dynamicDisabled: () => true,
  },
  {
    field: 'workQualityCriterion',
    label: '工作质量标准',
    component: 'InputTextArea',
    dynamicDisabled: () => true,
    show: true,
    colProps: { span: 24 },
  },
];

const workTree = {
  url: getWorkTreeApi,
  method: 'post', //请求方法类型 默认get
  title: '项目和类型',
  params: {
    orgCode: pageParams.value.orgCode,
    periodCode: pageParams.value.orgCode,
  },
  fieldNames: {
    title: 'title', //替换树默认显示title字段
    key: 'code',
  },
  disabledAll: false,
  disabled: false,
};

const userTree = ref({
  url: getUserTreeApi,
  method: 'post', //请求方法类型 默认get
  title: '参与人员选择',
  params: {
    orgCode: pageParams.value.orgCode,
  },
  // checkable: true,
  fieldNames: {
    title: 'psnName', //替换树默认显示title字段
    key: 'psnNum',
  },
  selectedKeys: [],
  showCheckAll: false,
  disabledAll: false,
  disabled: false,
});

let selectorField = ref([]);
let defaultData = {};
let editid = null;

// 声明Emits
const emit = defineEmits(['success', 'register']);
const [registerModal, { closeModal = () => { }, setModalProps = () => { } }] = useModalInner(async (data) => {
  okLoading.value = false;
  currentRationCode = '';
  pageParams.value.orgCode = data.orgCode;
  pageParams.value.periodCode = data.periodCode;
  getWorkTreeList({ orgCode: data.orgCode, periodCode: data.periodCode }).then((res) => {
    workTreeList.value = res;
  });
  editid = data.isEdit ? data.res.id : null;
  userTree.value.disabled = data.isView;
  workTree.disabled = data.isView;
  isView.value = data.isView;
  if (data.isEdit) {
    // 编辑状态
    let formSchema = [...taskForm];
    resetSchema(formSchema);
    setFieldsValue({
      workItemName: data.res.rationName,
      workItemCode: data.res.rationCode,
      endDate: dayjs(data.res.endDate),
      standardValue: data.res.stdscore,
      workQualityCriterion: data.res.qstandard,
    });
    selectedWork.rationName = data.res.rationName;
    selectedWork.rationCode = data.res.rationCode;
    selectedWork.rationType = data.res.rationType;
    workList.value.handleSelect(data.res.rationCode);
    userList.value.setTreeSelected(data.res.psnNum.split(','));
    currentRationCode = data.res.rationCode;
    let tableData = data.res.details || [];
    tableData = tableData.map((item) => {
      if (item.reamrk) {
        return {
          ...item,
          ...JSON.parse(item.reamrk),
        };
      }
    });
    setTableData(tableData);
  }
  //动态表头设置 getTeamResultOrderXsHeader
  await getColumn({ orgCode: pageParams.value.orgCode }).then((res) => {
    let columns = [...taskColumns];
    try {
      res.forEach((r) => {
        //默认值设置
        if (r.datas && r.datas.length > 0) {
          r.datas.forEach((option) => {
            option.workName = option.workName + '(' + option.workCode + ')';
            if (option.isDefault === 'true' && !data.isEdit) {
              defaultData[r.headCode] = option.workCode;
            }
          });
        }
        // 在表格固定表头中插入动态表头
        columns.splice(columns.length - 5, 0, {
          title: r.headName,
          dataIndex: r.headCode,
          editRow: true,
          editComponent: 'Select',
          type: 2,
          width: 100,
          align: 'center',
          options: r.datas,
        });
      });
      setColumns(columns); //重设表头
    } catch (e) {
      console.error(e);
    }
  });
});

//表单配置
const [
  registerForm,
  { setFieldsValue = () => { }, validate = () => { }, resetSchema = () => { }, getFieldsValue = () => { }, updateSchema = () => { } },
] = useForm({
  schemas: taskForm,
  showActionButtonGroup: false,
  labelWidth: 180,
});
let totalScore = ref(20); //项目总分
let scrollY = computed(() => {
  let width = document.body.clientWidth;
  return width < 1500 ? 400 : 500;
});

let [registerTable, { getDataSource = () => { }, setTableData = () => { }, setColumns = () => { }, getColumns = () => { } }] = useTable({
  columns: taskColumns,
  rowKey: 'id',
  bordered: true,
  showActionColumn: true,
  // actionColumn: {
  //   width: 120,
  //   fixed: 'right',
  // },
  actionColumn: {
    width: 60,
    title: '操作',
    dataIndex: 'action',
    slots: { customRender: 'action' },
    fixed: 'right',
  },
  pagination: false,
  scroll: { y: scrollY },
});

let rationFormValue = '3'; //工作标准类型 1代表数量积分 2代表 数量+质量积分 3代表质量积分
let currentRationCode = ''; //当前项目编码
let selectedUser = {
  addMode: '10',
};
let selectedWork = {
  rationCode: '',
  rationName: '',
  rationType: '',
};

//表单提交事件
async function handleSubmit() {
  try {
    let tableData = getDataSource();
    if (tableData.length === 0) {
      createMessage.error('数据不能为空！');
      return;
    }
    let flag = true;
    let psnNameList = [];
    let psnNumList = [];
    tableData.forEach((t) => {
      psnNameList.push(t.psnName);
      psnNumList.push(t.psnNum);
      if (!t.sumPoints) {
        flag = false;
      }
    });
    //校验积分是否有空值
    if (!flag) {
      createMessage.error('积分项不能为空');
      return;
    }
    setModalProps({ confirmLoading: true });
    //拼接参数
    let formValue = await validate();
    let saveData = {
      // ...selectedUser,
      ...selectedWork,
      addMode: '10',
      psnName: psnNameList.join(),
      psnNum: psnNumList.join(),
      orgName: tableData[0].orgName,
      orgCode: tableData[0].orgCode,
      endDate: dayjs(formValue.endDate).format('YYYY-MM-DD'),
      descr: formValue.workQualityCriterion,
      details: tableData,
      periodCode: pageParams.value.periodCode,
      qstandard: formValue.workQualityCriterion,
      stdscore: formValue.standardValue,
    };
    saveData.details?.forEach((item) => {
      // let sumScore = 0;
      item.reamrk = {};
      Object.keys(item).forEach((key) => {
        if (key.indexOf('XSP') != -1) {
          // sumScore += parseFloat(item[key]);
          item.reamrk = {
            ...item.reamrk,
            [key]: item[key],
            // sumPoints: sumScore,
          };
        }
        // item.sumPoints = sumScore;
      });
    });
    saveData.details?.forEach((item) => {
      item.addMode = '10';
      if (item.reamrk) {
        item.reamrk = JSON.stringify(item.reamrk);
      }
    });
    if (editid) {
      saveData.id = editid;
    }
    // changeLoading(true);
    // changeOkLoading(false);
    okLoading.value = true;
    save(saveData).then((res) => {
      if (res) {
        //关闭弹窗
        closeModal();
        okLoading.value = false;
        //刷新列表
        emit('success');
      }
    });
  } finally {
    setModalProps({ confirmLoading: false });
  }
}

/**
 * author:lhw
 * description: 项目树选择事件
 * @params: @
 * date: 2023/3/8
 * lastModify: 2023/3/8
 */
const handleWorkTreeSelect = (node) => {
  let workTypeDesc = workTreeList.value.filter((item) => item.code === node.data.parentCode)[0].title;
  setTableData([]); //清空表格数据
  userList.value.setTreeSelected([]); //清空用户选择数据
  let formSchema = [...taskForm];
  resetSchema(formSchema); //先要改变表单对象否则下次重填之前数据更新不上去
  currentRationCode = node.data.code;
  //判断是否可查询数据节点
  if (node.data.isRation) {
    selectedWork.rationCode = node.data.code;
    selectedWork.rationName = node.data.title;
    selectedWork.rationType = workTypeDesc;
    getTaskDetail({ code: node.data.id }).then(async (res) => {
      //表单赋值
      setFieldsValue(res); //得到标准工分 stdscore
    });
  }
};

const scoreCompute = () => {
  let TableData = getDataSource();
  let column = getColumns();
  // TableData[]
  let currentRecord = TableData[currentTableIndex];
  let workPoints = null;
  if (!currentRecord.unit) {
    // 次数没填时 工作量得分为0    workPoints 工作量得分   qspoints质量得分
    currentRecord.workPoints = 0;
    currentRecord.sumPoints = currentRecord.workPoints;
  } else {
    // currentRecord.workPoints = currentRecord.rationForm
    workPoints = currentRecord.unit;
    column.forEach((c) => {
      if (c.type && currentRecord[c.dataIndex]) {
        workPoints = currentRecord[c.dataIndex] * workPoints;
        // counts.push
      }
    });
    currentRecord.workPoints = workPoints;
    currentRecord.sumPoints = currentRecord.workPoints;
  }
  if (getFieldsValue().standardValue || getFieldsValue().standardValue == 0) {
    currentRecord.workPoints = currentRecord.workPoints * parseFloat(getFieldsValue().standardValue);
  }
  if (currentRecord.qspoints || currentRecord.qspoints == 0) {
    currentRecord.sumPoints = currentRecord.qspoints + currentRecord.workPoints;
  }
  if (!currentRecord.qspoints) {
    currentRecord.sumPoints = currentRecord.workPoints;
  }
  // 精度转化
  currentRecord.workPoints = unifyNumber(currentRecord.workPoints);
  currentRecord.sumPoints = unifyNumber(currentRecord.sumPoints);
};

let selectPerson = [];

//右侧人员树选择事件----湖北
const handleUserTreeSelect = (node) => {
  if (!currentRationCode) {
    createMessage.warning('请先选择左侧项目类型');
    // checkedKeys = [];
    userList.value.setTreeSelected([]);
    return;
  }
  // let nodes = checkedKeys.e.checkedNodes;
  let selectData = JSON.parse(JSON.stringify(node.data));
  selectPerson = getDataSource();
  let formData = getFieldsValue();
  let sumPoints = 1;
  Object.values(defaultData).forEach((value) => {
    sumPoints = unifyNumber(parseFloat(value) * sumPoints);
  });
  sumPoints = unifyNumber(sumPoints * parseFloat(formData.standardValue));
  selectPerson.push({
    psnNum: selectData.psnNum,
    psnName: selectData.psnName,
    orgCode: selectData.orgCode,
    orgName: selectData.orgName,
    unit: 1,
    sumPoints,
    workPoints: sumPoints,
    ...defaultData,
  });
  let newData = [];
  let originData = getDataSource() || [];
  let psnNums = [];
  let psnNames = [];
  let newPsnNums = [];
  let newPsnNames = [];
  let orgCodes = [];
  let orgNames = [];
  selectPerson.forEach((n, i) => {
    // let temp = {
    //   psnNum: n.psnNum,
    //   psnName: n.psnName + i,
    //   orgCode: n.orgCode,
    //   orgName: n.orgName,
    //   unit: 1,
    //   sumPoints,
    //   workPoints: sumPoints,
    //   ...defaultData,
    // };
    psnNums.push(n.psnNum);
    psnNames.push(n.psnName);
    newPsnNums = Array.from(new Set(psnNums));
    newPsnNames = Array.from(new Set(psnNames));
    orgCodes.push(n.orgCode);
    orgNames.push(n.orgName);
    // 新表格数据 原有的数据需要保留
    // originData.forEach((d) => {
    //   if (d['psnNum'] == temp.psnNum) {
    //     temp = Object.assign(d);
    //   }
    // });
    // newData.push(temp);
  });
  //数据保存需要添加的参数
  selectedUser = {
    ...selectedUser,
    psnNum: newPsnNums.join(','),
    psnName: newPsnNames.join(','),
    orgCode: orgCodes[0] || '',
    orgName: orgNames[0] || '',
  };
  //重填表格数据
  setTableData(selectPerson);
};



const getTableAction = (record, index) => {
  return [
    {
      label: '删除',
      onClick: handleDelete.bind(null, record, index),
    },
  ];
};

const handleDelete = async (record, index) => {
  let tableData = getDataSource();
  tableData.splice(index, 1);
  setTableData(tableData);
  // if (!record.id) {
  //   tableData.splice(index, 1);
  //   setTableData(tableData);
  // } else {
  //   await deleteOne({ id: record.id }, handleSuccess);
  // }
  // await deleteOne({ id: record.id }, handleSuccess);
};
</script>

<style scoped lang="less">
.table-container {
  height: 750px;
}

@media screen and(max-width: 1650px) {
  .table-container {
    height: 650px;
  }
}

@media screen and(max-width: 1500px) {
  .table-container {
    height: 600px;
  }
}

.bot-container {
  display: flex;
}

.bot-table-container {
  width: calc(100% - 250px);
  height: 700px;
}

/deep/.ant-input-number {
  width: 100%;
}

/deep/.ant-picker {
  width: 100%;
}
</style>
